module.exports = {
    /**
     * mapSelectOpions 将给定的list处理成组件的select的option字段
     * @param  {array} list      给定的list
     * @param  {string} valueName valueName
     * @param  {string} labelName labelName
     * @return {array}           处理完成的list
     */
    mapSelectOpions: function(list, valueName, labelName) {
        if (!list || !valueName || !labelName) {
            return [];
        }

        return list.map((item) => {
            const newItem = Object.assign({}, item);
            const value = newItem[valueName];
            const label = newItem[labelName];

            delete newItem[valueName];
            delete newItem[labelName];
            
            return Object.assign({}, newItem, {
                value,
                label,
            });
        });
    },

    /**
     * debounce 自实现debounce函数
     * @param  {function} fn    要延迟执行的函数
     * @param  {number}   delay 延迟时间
     * @return {function}         debounce函数
     */
    debounce: function(fn, delay) {
        let timer = null;
        return function (...args) { // eslint-disable-line
            const context = this;
            clearTimeout(timer);
            timer = setTimeout(function () { // eslint-disable-line
                fn.apply(context, args);
            }, delay);
        };
    },

    /**
     * operateParams 对目标参数进行新增或删除操作
     * @param  {object} params 父参数（请求参数或返回参数）
     * @param  {string} operateType  操作类型
     * @param  {string} trId         参数行标识
     */
    operateParams(params, operateType, trId) {
        let targetParamList = params;

        // 添加顶级参数
        if (!trId) {
            targetParamList.push({
                identifier: '',
                name: '',
                remark: '',
                dataType: 'string',
                canEmpty: false,
                paramList: [],
            });
            return;
        }

        const trIdLen = trId.length;
        const trIdArr = trId.split('');

        trIdArr.forEach((item, index) => {

            const trIdItem = parseInt(item, 10);

            if (index === trIdLen - 1) {

                if (operateType === 'delete') {

                    targetParamList.splice(trIdItem, 1);

                } else if (operateType === 'add') {

                    targetParamList[trIdItem].paramList.push({
                        identifier: '',
                        name: '',
                        remark: '',
                        dataType: 'string',
                        canEmpty: false,
                        paramList: [],
                    });
                }

            } else {
                targetParamList = targetParamList[trIdItem].paramList;
            }
        });
    },
};
